import { Context } from 'koa';
import { AppDataSource } from '@/config/database';
import { Order, OrderService, OrderPointsUsage, OrderStoredValueUsage, OrderGroupBuyUsage, CustomerPoints, CustomerStoredValueCard } from '@/entities';

/**
 * 订单控制器
 */
export class OrderController {
    
    /**
     * 创建订单
     */
    static async createOrder(ctx: Context) {
        try {
            const {
                customerId,
                services, // 服务列表 [{serviceId, quantity, unitPrice}]
                pointsUsage, // 积分使用 [{customerPointsId, usedPointsAmount, exchangeRate}]
                storedValueUsage, // 储值卡使用 [{customerStoredValueCardId, usedAmount}]
                groupBuyUsage, // 团购使用 [{groupBuyPlatform, groupBuyOrderNumber, usedAmount, groupBuyVoucherCode?, originalPrice?}]
                discountAmount,
                discountReason,
                giftPoints,
                remark
            } = ctx.request.body;

            // 开启事务
            const queryRunner = AppDataSource.createQueryRunner();
            await queryRunner.connect();
            await queryRunner.startTransaction();

            try {
                // 1. 创建订单主记录
                const orderRepository = queryRunner.manager.getRepository(Order);
                const orderNumber = `ORD${Date.now()}`; // 简单的订单号生成逻辑
                
                let totalAmount = 0;
                let pointsDeductionAmount = 0;
                let storedValueDeductionAmount = 0;

                // 计算服务总金额
                for (const service of services) {
                    totalAmount += service.quantity * service.unitPrice;
                }

                // 计算积分抵扣金额
                if (pointsUsage && pointsUsage.length > 0) {
                    for (const points of pointsUsage) {
                        pointsDeductionAmount += points.usedPointsAmount * points.exchangeRate;
                    }
                }

                // 计算储值卡抵扣金额
                if (storedValueUsage && storedValueUsage.length > 0) {
                    for (const stored of storedValueUsage) {
                        storedValueDeductionAmount += stored.usedAmount;
                    }
                }

                // 计算团购支付总金额
                let groupBuyPaymentAmount = 0;
                if (groupBuyUsage && groupBuyUsage.length > 0) {
                    for (const groupBuy of groupBuyUsage) {
                        groupBuyPaymentAmount += groupBuy.usedAmount;
                    }
                }

                // 计算现金支付金额（总金额 - 折扣 - 积分抵扣 - 储值卡抵扣 - 团购支付）
                const cashPaymentAmount = totalAmount - (discountAmount || 0) - pointsDeductionAmount - storedValueDeductionAmount - groupBuyPaymentAmount;

                const order = orderRepository.create({
                    orderNumber,
                    customerId,
                    totalAmount,
                    discountAmount: discountAmount || 0,
                    discountReason,
                    pointsDeductionAmount,
                    storedValueDeductionAmount,
                    cashPaymentAmount,
                    groupBuyPaymentAmount,
                    giftPoints: giftPoints || 0,
                    orderStatus: 'pending',
                    remark
                });

                const savedOrder = await orderRepository.save(order);

                // 2. 创建订单服务明细
                const orderServiceRepository = queryRunner.manager.getRepository(OrderService);
                for (const service of services) {
                    const orderService = orderServiceRepository.create({
                        orderId: savedOrder.id,
                        serviceId: service.serviceId,
                        quantity: service.quantity,
                        unitPrice: service.unitPrice,
                        totalPrice: service.quantity * service.unitPrice
                    });
                    await orderServiceRepository.save(orderService);
                }

                // 3. 创建积分使用记录
                if (pointsUsage && pointsUsage.length > 0) {
                    const pointsUsageRepository = queryRunner.manager.getRepository(OrderPointsUsage);
                    const customerPointsRepository = queryRunner.manager.getRepository(CustomerPoints);
                    
                    for (const points of pointsUsage) {
                        // 创建使用记录
                        const pointsUsageRecord = pointsUsageRepository.create({
                            orderId: savedOrder.id,
                            customerPointsId: points.customerPointsId,
                            usedPointsAmount: points.usedPointsAmount,
                            deductionAmount: points.usedPointsAmount * points.exchangeRate,
                            exchangeRate: points.exchangeRate
                        });
                        await pointsUsageRepository.save(pointsUsageRecord);

                        // 更新积分余额
                        const customerPoints = await customerPointsRepository.findOne({
                            where: { id: points.customerPointsId }
                        });
                        if (customerPoints) {
                            customerPoints.remainingPoints -= points.usedPointsAmount;
                            await customerPointsRepository.save(customerPoints);
                        }
                    }
                }

                // 4. 创建储值卡使用记录
                if (storedValueUsage && storedValueUsage.length > 0) {
                    const storedValueUsageRepository = queryRunner.manager.getRepository(OrderStoredValueUsage);
                    const storedValueCardRepository = queryRunner.manager.getRepository(CustomerStoredValueCard);
                    
                    for (const stored of storedValueUsage) {
                        const storedValueCard = await storedValueCardRepository.findOne({
                            where: { id: stored.customerStoredValueCardId }
                        });
                        
                        if (storedValueCard) {
                            const balanceBefore = storedValueCard.currentBalance;
                            const balanceAfter = balanceBefore - stored.usedAmount;

                            // 创建使用记录
                            const storedValueUsageRecord = storedValueUsageRepository.create({
                                orderId: savedOrder.id,
                                customerStoredValueCardId: stored.customerStoredValueCardId,
                                usedAmount: stored.usedAmount,
                                balanceBefore,
                                balanceAfter
                            });
                            await storedValueUsageRepository.save(storedValueUsageRecord);

                            // 更新储值卡余额
                            storedValueCard.currentBalance = balanceAfter;
                            await storedValueCardRepository.save(storedValueCard);
                        }
                    }
                }

                // 5. 保存团购使用记录
                if (groupBuyUsage && groupBuyUsage.length > 0) {
                    const groupBuyUsageRepository = queryRunner.manager.getRepository(OrderGroupBuyUsage);
                    
                    for (const groupBuy of groupBuyUsage) {
                        const groupBuyUsageRecord = groupBuyUsageRepository.create({
                            orderId: savedOrder.id,
                            usedAmount: groupBuy.usedAmount,
                            groupBuyPlatform: groupBuy.groupBuyPlatform,
                            groupBuyOrderNumber: groupBuy.groupBuyOrderNumber,
                            groupBuyVoucherCode: groupBuy.groupBuyVoucherCode,
                            originalPrice: groupBuy.originalPrice,
                            remark: groupBuy.remark
                        });
                        await groupBuyUsageRepository.save(groupBuyUsageRecord);
                    }
                }

                // 6. 如果有赠送积分，创建积分记录
                if (giftPoints && giftPoints > 0) {
                    const customerPointsRepository = queryRunner.manager.getRepository(CustomerPoints);
                    const giftPointsRecord = customerPointsRepository.create({
                        customerId,
                        batchNumber: `GIFT${Date.now()}`,
                        pointsAmount: giftPoints,
                        remainingPoints: giftPoints,
                        sourceType: '订单赠送',
                        sourceDescription: `订单${orderNumber}赠送积分`,
                        status: 'active'
                    });
                    await customerPointsRepository.save(giftPointsRecord);
                }

                // 提交事务
                await queryRunner.commitTransaction();

                ctx.status = 201;
                ctx.body = {
                    success: true,
                    message: '订单创建成功',
                    data: {
                        orderId: savedOrder.id,
                        orderNumber: savedOrder.orderNumber
                    }
                };

            } catch (error) {
                // 回滚事务
                await queryRunner.rollbackTransaction();
                throw error;
            } finally {
                // 释放查询运行器
                await queryRunner.release();
            }

        } catch (error) {
            console.error('创建订单失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '创建订单失败',
                error: error.message
            };
        }
    }

    /**
     * 获取订单详情
     */
    static async getOrderDetail(ctx: Context) {
        try {
            const { orderId } = ctx.params;
            
            const orderRepository = AppDataSource.getRepository(Order);
            const order = await orderRepository.findOne({
                where: { id: orderId },
                relations: [
                    'customer',
                    'services',
                    'services.service',
                    'pointsUsages',
                    'pointsUsages.customerPoints',
                    'storedValueUsages',
                    'storedValueUsages.customerStoredValueCard',
                    'groupBuyUsages'
                ]
            });

            if (!order) {
                ctx.status = 404;
                ctx.body = {
                    success: false,
                    message: '订单不存在'
                };
                return;
            }

            ctx.body = {
                success: true,
                data: order
            };

        } catch (error) {
            console.error('获取订单详情失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取订单详情失败',
                error: error.message
            };
        }
    }
} 